<template>
	<view class="container" :style="[containHeight]">
		<view class="search-content">
			<view class="search-item">
				<text class="search-label">考试人群名称：</text>
				<u--input placeholder="请输入考试人群名称" border="surround" v-model="searchParams.crowdName"></u--input>
			</view>
			<view class="btn-group">
				<u-button text="查询" type="primary" :loading="btnSearch" loadingText="查询中" class="search-btn"
					@click="toSearch"></u-button>
			</view>
		</view>
		<view class="content">
			<view class="delItem layout-start">
				<u-button text="创建人群" color="linear-gradient(to right, #7774ff, #017ffd,#01b1fd)"
					@click="newcrowd()"></u-button>
			</view>
			<view v-if="crowdList.length==0">
				<u-empty mode="list" icon="../../static/listEmpty.png"></u-empty>
			</view>
			<u-swipe-action v-for="(item,index) in crowdList" :key="index" autoClose v-else>
				<u-swipe-action-item :options="optionscrowd" @click="swipeItem(item,$event)">
					<view class="historicalAchievements_item u-border-bottom">
						<text class="bold">考试人群名称：</text>
						<text>{{item.crowdName}}</text>
						<view class="includePeopleTxt" @click="morePeople(item.includePeoples)">
							<text class="bold">考试人:</text>
							<text>{{Array.isArray(item.includePeoples) ?  item.includePeoples.join(','):item.includePeoples}}
							</text>
						</view>
					</view>
				</u-swipe-action-item>
			</u-swipe-action>
			<u-loadmore :status="statusLoading" v-if="crowdList.length!=0" />
		</view>
		<u-popup :show="isNewEdit" mode="center" closeable @close="closeNewEdit">
			<view class="popupContent">
				<view class="popupTitle">{{formTitle == 0 ? '创建人群' : '编辑人群'}}</view>
				<u--form labelPosition="left" labelWidth="95" :model="formPopup" :rules="rules" ref="uForm">
					<u-form-item label="考试人群名称" prop="crowdName" required>
						<u--input placeholder="请输入考试人群名称" border="surround" v-model="formPopup.crowdName"></u--input>
					</u-form-item>
					<u-form-item label="考试人部门(仅筛选)" prop="includeDeptCodes">
						<zxz-uni-data-select :multiple="true" :localdata="options.deptCodes.list" placeholder="请选择部门"
							v-model="formPopup.includeDeptCodes" dataKey="key" dataValue="value" collapseTags
							@change="changeDept">
						</zxz-uni-data-select>
					</u-form-item>
					<u-form-item label="考试人工种(仅筛选)" prop="includeJobType">
						<zxz-uni-data-select :multiple="true" :localdata="options.jobType.list" placeholder="请选择工种"
							v-model="formPopup.includeJobType" dataKey="key" dataValue="value" collapseTags
							@change="changeJobType">
						</zxz-uni-data-select>
					</u-form-item>
					<u-form-item label="违章类型(仅筛选)" prop="type">
						<zxz-uni-data-select :localdata="options.violationType.list" placeholder="请选择违章类型"
							v-model="formPopup.type" dataKey="key" dataValue="value"
							@change="changeViolationType">
						</zxz-uni-data-select>
					</u-form-item>
					<u-form-item label="时间范围(仅筛选)" prop="time">
						<zxz-uni-data-select :localdata="options.time" placeholder="请选择时间范围"
							v-model="formPopup.time" dataKey="key" dataValue="value"
							@change="changeTime">
						</zxz-uni-data-select>
					</u-form-item>
					<u-form-item label="安全意识等级(仅筛选)" prop="riskPeople">
						<zxz-uni-data-select :localdata="options.results" placeholder="请选择安全意识等级(仅筛选)"
							v-model="formPopup.riskPeople" dataKey="key" dataValue="value" @change="isResultsConfirm">
						</zxz-uni-data-select>
						<!-- <u-picker :show="isRiskPeople" :columns="options.results" v-model="formPopup.riskPeople"
							@confirm="isResultsConfirm" @cancel="isRiskPeople=false" keyName="label"></u-picker>
						<view class="select-border" @click="isRiskPeople=true">
							<text v-if="!formPopup.riskPeople">请选择安全意识等级(仅筛选)</text>
							<text v-if="formPopup.riskPeople" class="selectedTxt">
								<text v-if="formPopup.riskPeople=='高风险'">安全意识一般</text>
								<text v-else-if="formPopup.riskPeople=='中风险'">安全意识适中</text>
								<text v-else-if="formPopup.riskPeople=='低风险'">安全意识较强</text>
								<text v-else>{{formPopup.riskPeople}}</text>
							</text>
						</view> -->
					</u-form-item>
					<u-form-item label="考试人姓名(仅筛选)" prop="name">
						<u--input placeholder="请输入考试人姓名(仅筛选)" border="surround" v-model="formPopup.name"
							@change="changeName"></u--input>
					</u-form-item>					
					<u-form-item label="考试人" prop="includePeoples" class="mB80" required>
						<zxz-uni-data-select :multiple="true" :localdata="options.peoples.list" placeholder="请选择考试人"
							v-model="formPopup.includePeoples" dataKey="key" dataValue="value" collapseTags
							@change="changePeople">
						</zxz-uni-data-select>
					</u-form-item>
				</u--form>
				<view class="btn-group absolutePosition">
					<u-button text="取消" class="reset-btn" @click="cancelCrowd('uForm')"></u-button>
					<u-button text="确认" type="primary" class="search-btn" @click="confirmcrowd('uForm')"></u-button>
				</view>
			</view>
		</u-popup>
		<u-popup :show="isPeoples" mode="center" closeable @close="isPeoples=false">
			<view class="popupPeople">
				<view class="popupTitle">考试人</view>
				<view>{{Array.isArray(peopleDetail) ?  peopleDetail.join(','):peopleDetail}}</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		examCrowdMain,
		selectCrowd,
		selectDeptName,
		selectJobType,
		selectPeoples,
		examCrowdAdd,
		examCrowdUpdate,
		examCrowdDelete,
		violationType
	} from "../../utils/api.js"
	export default {
		data() {
			return {
				fullHeight: true,
				crowdList: [],
				searchParams: {
					crowdName: '',
				},
				btnSearch: false,
				optionscrowd: [{
					text: '编辑',
					style: {
						backgroundColor: '#3c9cff'
					}
				}, {
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				isNewEdit: false,
				formTitle: 0, // 0-创建/1-编辑
				formDialog: {
					crowdName: "",
				},
				total: null, //总条数
				page: 1, //当前页码
				pageSize: 10, //每页显示数量
				statusLoading: 'loadmore',
				nextQuery: false,
				onlyReachBottom: true,
				formPopup: {
					id: "",
					crowdName: "",
					includeDeptCodes: [], //考试人群包含的部门code列表
					includeJobType: [], // 考试人群包含的工种
					name: "",
					includePeoples: [], //考试人的user列表
					riskPeople: "low",
					type: '',
					time:'',
				},
				rules: {
					crowdName: [{
						required: true,
						message: "请输入考试人群名称",
						trigger: "blur"
					}, ],
					includePeoples: [{
						required: true,
						message: "请选择考试人",
						trigger: "change"
					}, ],
				},
				isPeoples: false,
				peopleDetail: '',
				options: {
					deptCodes: {
						list: [],
						checked: false,
					},
					jobType: {
						list: [],
						checked: false,
					},
					peoples: {
						list: [],
						checked: false,
					},
					violationType: {
						list: [],
						checked: false,
					},
					results: [{
							key: "安全薄弱人员",
							value: 'high',//高风险
						},
						{
							key: "安全预警人员",
							value: 'medium',//中风险
						},
						{
							key: "安全放心人员",
							value: 'low',//低风险
						}
					],
					time: [{
							key: "当天",
							value: '',
						},
						{
							key: "一周",
							value: '',
						},
						{
							key: "一个月",
							value: '',
						}
					],
				},
				isRiskPeople: false,
				//仅用于像后端传递数据
				paramsValue: {
					includeDepCodes: '',
					includeJobType: null,
					risk: '',
					name: '',
					type: '',
					time:'',
				},
			}
		},
		onLoad() {
			this.userId = uni.getStorageSync('userinfo').id
			this.getcrowdList()
			this.getOptions()
			this.updateTime()
		},
		computed: {
			containHeight() {
				return this.fullHeight ? {
					/*#ifdef MP-WEIXIN*/
					// 微信小程序特有代码
					height: '100vh',
					/*#endif*/
					/*#ifndef MP-WEIXIN*/
					height: 'calc(100vh - 44px)'
					/*#endif*/
				} : {
					height: '100%'
				}
			},
		},
		onReachBottom() {
			if (this.fullHeight) {
				this.fullHeight = false
			}
			if (this.nextQuery) {
				//搜索结果
				this.btnSearch = false
				selectCrowd({
					crowdName: this.searchParams.crowdName
				}).then(s => {
					if (s.code === 20000) {
						this.crowdList = s.data
						this.onlyReachBottom = false
						this.statusLoading = 'nomore'
					} else {
						uni.showToast({
							title: s.message,
							icon: 'none'
						})
					}
				})
			} else if (this.onlyReachBottom) {
				if (this.page * this.pageSize < this.total) {
					this.statusLoading = 'loading'
					this.page++
					this.getcrowdList()
					// console.log("onReachBottom");
				} else {
					this.statusLoading = 'nomore'

				}
			} else {
				// console.log("什么也不做");
			}
		},
		methods: {
			getcrowdList(isdel) {
				examCrowdMain({
					pageSize: this.pageSize,
					page: this.page,
				}).then(s => {
					if (s.code === 20000) {
						if (isdel == 'ture') {
							//删除操作
							this.crowdList = s.data.records
						} else {
							this.crowdList = this.crowdList.concat(s.data.records)
						}
						this.total = s.data.total
						if (this.total < this.pageSize) {
							this.statusLoading = 'nomore'
						}
					} else {
						uni.showToast({
							title: s.message,
							icon: "none"
						})
					}
				})
			},
			toSearch() {
				this.btnSearch = true
				this.onlyReachBottom = false
				this.crowdList = []
				selectCrowd({
					crowdName: this.searchParams.crowdName
				}).then(s => {
					// console.log("查询s", s);
					if (s.code === 20000) {
						//搜索结果反映到视图
						this.btnSearch = false
						this.crowdList = s.data
						this.nextQuery = true
						this.page = 1
					} else {
						uni.showToast({
							title: s.message,
							icon: 'none'
						})
					}
				})
			},
			swipeItem(item, e) {
				// console.log("swipeItem e", e);
				console.log("item", item);
				if (e.index == 0) {
					//编辑
					this.isNewEdit = true
					this.formTitle = 1
					this.formPopup = item
					this.formPopup.includePeoples = this.formPopup.includePeoples.split(',').map((item) => item)
					//获取所有的考试人
					selectPeoples().then(s => {
						if (s.code === 20000) {
							this.options.peoples.list = s.data.map(item => ({
								key: item,
								value: item
							}));
						} else {
							uni.showToast({
								title: s.message,
								icon: "none"
							})
						}
					})

				} else if (e.index == 1) {
					//删除
					let that = this
					uni.showModal({
						title: '提示',
						content: '此操作将永久删除该题库, 是否继续?',
						success: function(res) {
							if (res.confirm) {
								examCrowdDelete({
									id: item.id
								}).then(s => {
									if (s.code === 20000) {
										uni.showToast({
											title: '删除成功',
											icon: 'success'
										})
										that.getcrowdList('ture')
									} else {
										uni.showToast({
											title: s.message,
											icon: 'none'
										})
									}
								})
							} else if (res.cancel) {
								// console.log('用户点击取消');
							}
						}
					});
				} else {

				}
			},
			newcrowd() {
				this.isNewEdit = true
				this.formTitle = 0;

			},
			confirmcrowd() {
				this.isNewEdit = false
				if (this.formTitle == 0) {
					//创建
					examCrowdAdd({
						crowdName: this.formPopup.crowdName,
						includeDeptCodes: this.formPopup.includeDeptCodes,
						includeJobType: this.formPopup.includeJobType,
						includePeoples: this.formPopup.includePeoples.toString(),
					}).then(s => {
						if (s.code === 20000) {
							uni.showToast({
								title: '创建成功',
								icon: 'success'
							})
							this.getcrowdList()
						} else {
							uni.showToast({
								title: s.message,
								icon: 'none'
							})
						}
					})
				} else if (this.formTitle == 1) {
					//编辑
					examCrowdUpdate({
						id: this.formPopup.id,
						crowdName: this.formPopup.crowdName,
						includeDepCodes: this.formPopup.includeDeptCodes,
						includeJobType: this.formPopup.includeJobType,
						includePeoples: this.formPopup.includePeoples.toString(),
					}).then(s => {
						if (s.code === 20000) {
							uni.showToast({
								title: '更新成功',
								icon: 'success'
							})
						} else {
							uni.showToast({
								title: s.message,
								icon: 'none'
							})
						}
					})
				}
			},
			cancelCrowd(formName) {
				this.isNewEdit = false
				this.$refs[formName].resetFields()
			},
			morePeople(people) {
				this.isPeoples = true
				this.peopleDetail = people
			},
			// 获取下拉列表
			getOptions() {
				selectDeptName().then(s => {
					if (s.code === 20000) {
						this.options.deptCodes.list = s.data.map(item => ({
							key: item,
							value: item
						}));
					} else {
						uni.showToast({
							title: s.message,
							icon: "none"
						})
					}
				})
				selectJobType().then(s => {
					if (s.code === 20000) {
						this.options.jobType.list = s.data.map(item => ({
							key: item,
							value: item
						}));
					} else {
						uni.showToast({
							title: s.message,
							icon: "none"
						})
					}
				})
				violationType().then(s => {
					if (s.code === 20000) {
						this.options.violationType.list = s.data.map(item => ({
							key: item,
							value: item
						}));
					} else {
						uni.showToast({
							title: s.message,
							icon: "none"
						})
					}
				})
			},
			changeDept(e) {
				// console.log("e:", e);
				//有值时
				if (this.formPopup.includeDeptCodes) {
					this.getSelectPeople()
				}
			},
			isResultsConfirm(val) {
				// this.isRiskPeople = false
				// this.formPopup.riskPeople = val.value[0].label
				if (this.formPopup.riskPeople && this.formPopup.time) {
					this.getSelectPeople()
				}
			},
			changeJobType() {
				//有值时
				if (this.formPopup.includeJobType) {
					this.getSelectPeople()
				}

			},
			changeViolationType() {
				if (this.formPopup.type) {
					this.getSelectPeople()
				}
			},
			changeTime(){
				if (this.formPopup.riskPeople &&this.formPopup.time) {
					this.getSelectPeople()
				}
			},
			changePeople(e) {
				// console.log("changePeople",e);
				// this.getSelectPeople()
			},
			getSelectPeople() {
				//处理参数向后端查询数据
				this.paramsValue.includeDeptCodes = this.formPopup.includeDeptCodes
				this.paramsValue.includeJobType = this.formPopup.includeJobType
				this.paramsValue.risk = this.formPopup.riskPeople
				this.paramsValue.name = this.formPopup.name
				this.paramsValue.type = this.formPopup.type
				this.paramsValue.time = this.formPopup.time
				//过滤空的参数、空数组				
				const params = Object.keys(this.paramsValue)
					.filter((key) => {
						const value = this.paramsValue[key];
						return value !== null && value !== '' && value !== undefined && (Array.isArray(value) ? value
							.length > 0 : true);
					})
					.reduce((acc, key) => ({
						...acc,
						[key]: this.paramsValue[key]
					}), {});
				selectPeoples(params).then(s => {
					if (s.code === 20000) {
						this.options.peoples.list = s.data.map(item => ({
							key: item,
							value: item
						}));
					} else {
						uni.showToast({
							title: s.message,
							icon: "none"
						})
					}
				})
			},
			closeNewEdit() {
				this.formPopup = {}
				this.isNewEdit = false
			},
			changeName() {
				if (this.formPopup.name) {
					this.getSelectPeople()
				}
			},
			format(date) {
				var d = new Date(date);
				return (d.getFullYear() + "-" + ("0" + (d.getMonth() + 1)).slice(-2) + "-" + ("0" + d.getDate()).slice(-
				2));
			},
			updateTime() {
				let today = new Date();
				let lastWeek = new Date(today);
				lastWeek.setDate(today.getDate() - 7);
				let lastMonth = new Date(today);
				lastMonth.setMonth(today.getMonth() - 1);
				this.options.time = [{
						key: "当天",
						value: this.format(today)
					},
					{
						key: "一周",
						value: this.format(lastWeek)
					},
					{
						key: "一个月",
						value: this.format(lastMonth)
					}
				]
			},
			
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background: linear-gradient(#5191FF 5%, #6AA2FF 8%, #BDD7FE 15%, #F6FAFF 100%);
		padding: 30rpx 30rpx;
		width: 100%;
		position: relative;
		box-sizing: border-box;

		.content {
			background: #ffffff;
			margin-top: 30rpx;
			padding: 30rpx 32rpx;
			box-sizing: border-box;
			border-radius: 15rpx;
			opacity: 0.9;
			width: 100%;
			position: relative;
		}
	}


	.historicalAchievements_item {
		background: #ffffff;
		box-sizing: border-box;
		padding: 30rpx;

		// border-radius: 20rpx;
		// box-shadow: 4px 4px 10px #888888;
		.line {
			height: 1rpx;
			background: #737375;
			width: 100%;
			margin: 30rpx 0rpx;
		}

	}


	.search-content {
		box-sizing: border-box;
		padding: 15rpx;
		width: 100%;
		position: relative;
		background: #ffffff;
		border-radius: 15rpx;

		.search-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			margin-top: 10rpx;
			font-size: 30rpx;
			box-sizing: border-box;
			padding: 10rpx 20rpx;

		}

		.search-label {
			max-width: 300rpx;
			overflow: hidden;
			// text-overflow: ellipsis;
			white-space: nowrap;
			font-size: 30rpx;
		}


	}

	.btn-group {
		display: flex;
		margin-top: 60rpx;
		width: 100%;
		position: relative;
		justify-content: space-between;

		.search-btn {
			width: 40%;
			border-radius: 100rpx;
			background: linear-gradient(to right, #7774ff, #017ffd, #01b1fd);
			color: #fff;
		}

		.reset-btn {
			width: 40%;
			border-radius: 100rpx;
		}

	}

	.bold {
		font-weight: 700;
		white-space: nowrap;
	}

	.delItem {
		width: 30%;
		padding-top: 20rpx;
		box-sizing: border-box;
		position: relative;
		margin-bottom: 20rpx;
	}

	.popupContent {
		margin-top: 20rpx;
		height: 1000rpx; // 固定高度
		overflow-y: scroll; // 超出滚动
		overscroll-behavior: none; // 禁止滚动溢出
		// color: #ffffff;
	}

	.popupPeople {
		margin-top: 20rpx;
		// height: 300rpx; // 固定高度
		// overflow-y: scroll; // 超出滚动
		// overscroll-behavior: none; // 禁止滚动溢出
	}

	/deep/.u-swipe-action-item__right {
		position: absolute;
		top: 1px;
		bottom: 1px;
		right: 1px;
	}



	.popupTitle {
		// font-weight: 900;
		white-space: nowrap;
		// line-height: 1.6;
		text-align: center;
		position: -webkit-sticky;
		position: sticky;
		top: 0;
		z-index: 2;
		// background: #ffffff;

		font-size: 32rpx;
		// font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
		font-weight: 700;
		// color: #5efff2;
		line-height: 42rpx;
		text-shadow: 4rpx 12rpx 16rpx rgba(0, 0, 0, .5);

	}

	.absolutePosition {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		// background-color: #ffffff;
		margin: 0rpx 0rpx 20rpx 0rpx;
		box-sizing: border-box;
		padding-top: 20rpx;
	}

	.mB80 {
		margin-bottom: 80rpx;
	}

	.includePeopleTxt {
		// width: 90%;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.select-border {
		width: 100%;
		height: 38px;
		line-height: 38px;
		border: 1px solid #dadbde;
		color: #B1B1B1;
		box-sizing: border-box;
		padding: 0rpx 25rpx;
		font-size: 16px;

		.selectedTxt {
			color: #ffffff !important; //rgb(48, 49, 51)
		}
	}

	/deep/.u-popup__content {
		width: 90%;
		position: relative;
		// padding: 40rpx;
		// box-sizing: border-box;
		overflow: auto;

		// background: rgba(16, 24, 55, .8) !important;
		// box-shadow: inset 0 0 20rpx 8rpx #3A78F2;
		// border-radius: 20rpx !important;
		// border: 4rpx solid #0ff;
		padding: 40rpx;
		box-sizing: border-box;
		// color: #ffffff;
	}

	// /deep/.u-form-item__body__left__content__label {
	// 	color: #ffffff !important;
	// }

	// /deep/.u-input__content__field-wrapper__field {
	// 	color: #ffffff !important;
	// }

	// /deep/.uni-select__input-text {
	// 	color: #ffffff;
	// }
</style>